package com.yingyi.org.service.impl;

import com.yingyi.basic.constant.ShopState;
import com.yingyi.basic.exception.BusinessException;
import com.yingyi.basic.service.impl.BaseServiceImpl;
import com.yingyi.basic.util.BaiduAuditUtils;
import com.yingyi.org.domain.Employee;
import com.yingyi.org.domain.Shop;
import com.yingyi.org.domain.ShopAuditLog;
import com.yingyi.org.dto.ShopDto;
import com.yingyi.org.mapper.EmployeeMapper;
import com.yingyi.org.mapper.ShopAuditLogMapper;
import com.yingyi.org.mapper.ShopMapper;
import com.yingyi.org.service.IEmployeeService;
import com.yingyi.org.service.IShopService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.List;

@Service
public class ShopServiceImpl extends BaseServiceImpl<Shop> implements IShopService {

    @Autowired
    private ShopMapper shopMapper;

    @Autowired
    private EmployeeMapper employeeMapper;


    @Autowired
    private ShopAuditLogMapper shopAuditLogMapper;

    @Autowired
    private JavaMailSender javaMailSender;

    @Autowired
    private IEmployeeService employeeService;
    /**
     * 店铺入驻：
     *  实现过程：
     *  1 数据有效性验证: 空参验证、输入密码相同验证、该店铺已经入驻的验证
     *  2 入驻
     *      2.1 先保存employee信息 t_employee，返回自增长的主键
     *      2.2 将2.1返回的自增主键保存到shop的admin_id字段，保存到t_shop中
     *      2.3 将2.2自增长的id更新到 admin对应的shop_id字段
     *
     * @param shop
     */
    @Override
    public void settlement(Shop shop) throws BusinessException {
        //1. 数据有效性验证
        Employee admin = shop.getAdmin();

        if (   StringUtils.isEmpty(shop.getName())
            || StringUtils.isEmpty(shop.getTel())
            || StringUtils.isEmpty(shop.getAddress())
            || StringUtils.isEmpty(shop.getLogo())
            || StringUtils.isEmpty(admin.getUsername())
            || StringUtils.isEmpty(admin.getPassword())
            || StringUtils.isEmpty(admin.getConfirmPassword())
            || StringUtils.isEmpty(admin.getEmail())
            || StringUtils.isEmpty(admin.getPhone())
        ){
            throw new BusinessException("数据不能为空！");
        }


        if( !admin.getPassword().equals(admin.getConfirmPassword())){
            throw new BusinessException("两次的密码不同");
        }

        if(!BaiduAuditUtils.textCensor(shop.getName())){
            throw new BusinessException("店铺名违规！");
        }


        Shop dbShop = shopMapper.queryByMessage(shop);
        if(dbShop != null){
            throw new BusinessException("店铺已经入驻，请直接登录！忘记密码请找回密码");
        }


        //2. 入驻业务
        //2.1 保存admin数据到t_employee,并且同步到t_logininfo中用于登录
        //employeeMapper.insert(admin);
        employeeService.insert(admin);

        //2.2 将2.1返回的自增主键保存到shop中
        shop.setAdmin_id(admin.getId());

        //2.3 保存shop到t_shop中
        shopMapper.insert(shop);

        //2.4 将2.3 返回的shop的自增长id保存到admin中
        admin.setShop_id(shop.getId());

        //2.5 更新admin中的shop_id字段
        employeeMapper.update(admin);
    }


    /**
     * 店铺审核成功
     * 后续操作流程：
     *  1 更新店铺的状态为待激活
     *  2 保存审核记录
     *  3 发送邮件通知用户
     *  由于审核成功和失败操作相同，封装为一个方法来操作！
     *
     *
     * @param log
     */
    @Override
    public void shopAuditPass(ShopAuditLog log) throws MessagingException {
        afterAuditing(true, log);
    }

    /**
     * 店铺审核失败，驳回
     * @param log
     */
    @Override
    public void shopAuditReject(ShopAuditLog log) throws MessagingException {
        afterAuditing(false, log);

    }

    /**
     * 成功激活，店铺入驻
     *  修改店铺的状态为【正常】
     * @param id
     */
    @Override
    public void active(Long id) {
        Shop shop = shopMapper.queryById(id);
        shop.setState(ShopState.NORMAL);

        shopMapper.update(shop);
    }

    @Override
    public void patchInsert(List<Shop> shops) {
        shopMapper.patchInsert(shops);
    }

    @Override
    public List<ShopDto> getEcharts() {
        return shopMapper.getEcharts();
    }


    /**
     * 1 更新店铺的状态为待激活
     * 2 保存审核记录
     * 3 发送邮件通知用户
     * @param status: 审核的结果 true for success, false for failure
     * @param log
     */
    private void afterAuditing(Boolean status, ShopAuditLog log) throws MessagingException {

        //查询关联的店铺
        Shop shop = shopMapper.queryById(log.getShop_id());

        if(shop == null){
            return;
        }


        String sendMesssage = null;
        if(status){
            //success

            //更新shop的状态
            shop.setState(ShopState.ACTIVATING);
            shopMapper.update(shop);

            //存储审核记录
            log.setState(ShopState.ACTIVATING);
            shopAuditLogMapper.insert(log);


            sendMesssage = "<h1>你的店铺已经注册!!!</h1><a href='http://localhost:8080/shop/active/"+log.getShop_id()+"'>点击该链接激活</a>";

        } else {

            //设置shop的状态
            shop.setState(ShopState.REJECTED);
            shopMapper.update(shop);

            log.setState(ShopState.REJECTED);

            //存储审核记录
            shopAuditLogMapper.insert(log);

            sendMesssage = "<h1>店铺入驻失败!!!</h1><a href='http://localhost:8081/#/shopRegister'>点击重新入驻</a>";

        }



        //发送邮件
        String email = employeeMapper.queryById(shop.getAdmin_id()).getEmail();


        //创建复杂邮件对象
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        //发送复杂邮件的工具类
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true,"utf-8");
        helper.setFrom("592412582@qq.com");
        helper.setSubject("店铺激活邮件");
        helper.setText(sendMesssage,true);

        //添加附件
        //helper.addAttachment("p73.jpg",new File("D:\\picture\\p73.jpg"));


        //收件人
        helper.setTo(email);
        javaMailSender.send(mimeMessage);

    }
}
